// pages/post/post.js
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    earnest_expresss_fee: 0.01,
    oder_no: parseInt('1006' + Math.random() * 100000000000000),

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      express_company_id: options.express_company_id,
      express_company: options.express_company,
      shopname: options.shopname,
      expresss_fee: wx.getStorageSync("configs").Price,
      Notice: wx.getStorageSync("configs").Notice,
      // addressee: wx.setStorageSync("oder_info").addressee,
      // building_number: wx.setStorageSync("oder_info").building_number,
      // addressee_phoneno: wx.setStorageSync("oder_info").addressee_phoneno,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this
    that.setData({
      oder_no: parseInt('1006' + Math.random() * 100000000000000),
    })
    if (wx.getStorageSync("post_oder_info")){
      var post_oder_info = wx.getStorageSync("post_oder_info")
      that.setData({
        addressee: post_oder_info.addressee,
        addressee_phoneno: post_oder_info.addressee_phoneno,
        building_number: post_oder_info.building_number,
        //earnest_expresss_fee: post_oder_info.earnest_expresss_fee,
        earnest_expresss_fee_num: post_oder_info.earnest_expresss_fee_num,
        idcard_no: post_oder_info.idcard_no,
        //oder_no: post_oder_info.oder_no,
        remarks: post_oder_info.remarks
      })
    }
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  check_idcard(res){
    console.log("检查身份证正则")
  },
  post_commit(res){
    console.log(res)
    console.log(res.detail.value)
    var that = this
    console.log(res)
    console.log(res.detail.value)
    var post_oder_info = res.detail.value
    // if (that.data.address.length < 2) {
    //   wx.showToast({
    //     title: '请先填写正确的配送信息/地址（备用）！',
    //     icon: 'none'
    //   })
    //   return
    // } else
     if (post_oder_info.addressee.length < 2) {
        wx.showToast({
          title: '请先填寄件人姓名！',
          icon: 'none'
        })
        return
      } else if (post_oder_info.building_number.length < 2) {
        wx.showToast({
          title: '请先填写楼号！',
          icon: 'none'
        })
        return
      } else if (post_oder_info.addressee_phoneno.length != 11) {
        wx.showToast({
          title: '手机号位数异常，请检查！',
          icon: 'none'
        })
        return
      }
    wx.setStorageSync("post_oder_info", post_oder_info)
    that.to_pay(post_oder_info);

  },
  to_pay(res) {
    console.log(res)
    var oder_info=res
    var that = this
   
    wx.showLoading({
      title: '支付中...',
      icon: "none",
      //duration: 2000,
      mask: true,
    })

    // 提交数据到订单
    const db = wx.cloud.database()
    db.collection("oder_Lists").add({
      data: {
        _id: oder_info.oder_no,
        oder_type:"post",
        build_number: oder_info.build_number,

        addressee: oder_info.addressee,
        addressee_phoneno: oder_info.addressee_phoneno,
        building_number: oder_info.building_number,
        express_company: oder_info.express_company,
        express_company_id: oder_info.express_company_id,
        expresss_fee: oder_info.earnest_expresss_fee,
        expresss_fee_num: oder_info.earnest_expresss_fee_num,
        oder_no: oder_info.oder_no,
        Alternate_address: "",
        shopname: that.data.shopname,
        verification_code: "",
        order_status: 0,
        //  timestamp: (Date.parse(new Date())) / 1000,

        idcard_no: oder_info.idcard_no,
        remarks: oder_info.remarks,
        // 默认为毫秒级别
        timestamp: Date.parse(new Date()),
        oder_time: util.formatTime_ymdhms(new Date()),
        oder_time_object: new Date(),


      },
      success(res) {
        //  wx.switchTab({
        //   url: '/pages/order/order',
        // })

        console.log(res)
        // wx.showToast({
        //   title: '支付中。。。',
        //   icon: "none",
        //   duration: 3000,
        //   success() {
        //     setTimeout(function () {
        //       wx.switchTab({
        //         url: '/pages/order/order',
        //       })
        //     }, 2000)
        //     //  wx.switchTab({
        //     //    url: '/pages/order/order',
        //     //  })
        //   },
        //   complete() {


        //   }
        // })
      }, fail(res) {
        console.log(res)

      }, complete(res) {
        console.log(res)


        //  wx.redirectTo({
        //    url: '/pages/order/order',
        //  })

      }
    })


    console.log(res)
    // console.log(res.currentTarget.dataset.info)
    //return
    var oder_info = res
    
    // return
    // 支付开始

    console.log(parseInt((parseFloat(oder_info.earnest_expresss_fee_num).toFixed(2)) * 100))
    console.log(oder_info.building_number + " 快递代取订单请注意！")
    console.log(oder_info.oder_no)
    console.log()
    console.log()

 
    wx.cloud.callFunction({
      name: "pay",
      data: {
        desc: oder_info.building_number + " 快递—邮寄—订单请注意！",
        orderid: "" + oder_info.oder_no,
        money: parseInt((parseFloat(oder_info.earnest_expresss_fee_num).toFixed(2)) * 100)
      },
      success(res) {
        console.log("提交成功", res.result)
        //that.pay(res.result)
        var payData = res.result
        //官方标准的支付方法
        wx.requestPayment({
          timeStamp: payData.timeStamp,
          nonceStr: payData.nonceStr,
          package: payData.package, //统一下单接口返回的 prepay_id 格式如：prepay_id=***
          signType: 'MD5',
          paySign: payData.paySign, //签名
          success(res) {
            wx.hideLoading()
            wx.showToast({
              title: '支付成功',
              icon: "none"
            })
            console.log("支付成功", res)
            // 支付成功更新订单状态为1
            that.update_oder_status(1, oder_info.oder_no)
              wx.switchTab({
          url: '/pages/order/order',
        })
          },
          fail(res) {
            console.log("支付失败", res)
            wx.hideLoading()
            if (res.errMsg =="requestPayment:fail cancel"){
              
              wx.showToast({
                title: '用户取消',
                icon: "none"
              })
            }else{
              wx.showToast({
                title: '支付失败',
                icon: "none"
              })
            }
            setTimeout(function(){
              wx.switchTab({
                url: '/pages/order/order',
              })
            },1000)
           
          },
          complete(res) {
            
            console.log("支付完成", res)
          }
        })
      },
      fail(res) {
        console.log("提交失败", res)
      }
    })

 



  },
  update_oder_status(status, _id) {
    var that = this
    console.log(status, _id)
    //  return
    //更新订单状态 
    const db = wx.cloud.database()
    const _ = db.command
    db.collection('oder_Lists').doc(_id).update({
      data: {
        order_status: status,
        // 更新支付状态时，同时更新支付时间戳
        timestamp: Date.parse(new Date()),
      },
      success() {
        wx.hideLoading()
        // 刷新页面
        // 待优化  可以在数据库修改后只改本地一个数据不用刷新页面
        that.onShow()
      },
      fail(res) {
        wx.showToast({
          title: '更新失败！',
          icon: "none",
          duration: 1500,
          mask: true

        })
      },
      complete(res) {
        console.log(res)
      }

    })
  },
  //实现小程序支付
  pay(payData) {
    console.log(payData)
    // appId: "wx03ceedc2340a7885"
    // nonceStr: "JIhW9Z7nAsFO3HHS"
    // package: "prepay_id=wx102207422989168db571dbec1537472700"
    // paySign: "48762284374046361CBD50ACF7F4442F"
    // signType: "MD5"
    // timeStamp: "1575986862"
    // timestamp: "1575986862"
    //官方标准的支付方法
    wx.requestPayment({
      timeStamp: payData.timeStamp,
      nonceStr: payData.nonceStr,
      package: payData.package, //统一下单接口返回的 prepay_id 格式如：prepay_id=***
      signType: 'MD5',
      paySign: payData.paySign, //签名
      success(res) {
        console.log("支付成功", res)
      },
      fail(res) {
        console.log("支付失败", res)
      },
      complete(res) {
        console.log("支付完成", res)
      }
    })
  },
})